package com.zjs.servlet;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;

@WebServlet(urlPatterns = {"/upload"})
public class UploadFileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建SmartUpload对象
        SmartUpload smartUpload = new SmartUpload();
        //初始化对象
        JspFactory defaultFactory = JspFactory.getDefaultFactory();
        PageContext pageContext = defaultFactory.getPageContext(this, req, resp, null, true, 1024, true);
        smartUpload.initialize(pageContext);
        //设置编码格式，要不然会报空指针异常
        smartUpload.setCharset("UTF-8");
        try {
            //上传文件
            smartUpload.upload();
            //获取文件
            File file = smartUpload.getFiles().getFile(0);
            //创建文件保存路径
            String filePath = "/myUploadFile/" + file.getFileName();
            //保存文件
            file.saveAs(filePath, File.SAVEAS_VIRTUAL);
            //获取其他传递过来的参数
            String name = smartUpload.getRequest().getParameter("name");
            //跳转页面
            req.setAttribute("name", name);
            req.setAttribute("imgName", file.getFileName());
            req.getRequestDispatcher("/success.jsp").forward(req, resp);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
    }
}
